export const form_init = function(from, to = {}) {
  if (from == null) {
    for (let attr in to) {
      to[attr] = null;
    }
  } else {
    to = copy(from, to);
  }
  return to;
}

export const from_init = form_init;

/*
 * JS里，给对象和数组赋值是引用，这里实现的是数据的copy
 * 注意：当你传入to变量，请确保to与from的数据结构一致
 */
export const copy = function(from, to = {}) {
  for (let attr in from) {
    to[attr] = from[attr];
  }

  return to;
}

// 同上，处理深层copy
export const copy_deep = function(from, to = {}) {
  for (let attr in from) {
    if (typeof from[attr] == 'Object')
      to[attr] = copy_deep(from[attr], to[attr]);
  }
  return to;
}

export const datetime_format = function(date, fmt) {
  if (!date) return;
  if (typeof date == "string")
    date = new Date(date);

  var o = {
    "m+": date.getMonth() + 1,  //月份 
    "d+": date.getDate(),       //日 
    "h+": date.getHours(),      //小时 
    "i+": date.getMinutes(),    //分 
    "s+": date.getSeconds(),    //秒 
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
    "S": date.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

export const get_filter_params = function(filter) {
  let temp = {};
  for (let item in filter) {
    if (filter[item] === null || typeof filter[item] === 'undefined' || filter[item] === '' || (filter[item].length > 0 && !filter[item][0])) {
      continue;
    } else {
      temp[item] = filter[item];
    }
  }
  return temp;
}

export const reset_filter_params = function(filter) {
  for (let item in filter) {
    if (filter[item] instanceof Array)
      filter[item] = [];
    else
      filter[item] = null;
  }
  return filter;
}

import Vue from 'Vue'
import axios from 'axios'
import Qs from 'qs'
import {
  Notification
} from 'element-ui';

axios.defaults.withCredentials = true
Vue.prototype.$ajax = axios

// 开发环境 development
// 测试环境 testing
// 预发布环境 pre-product
// 生产环境 product
// http://localhost:8080
export const getApiRoot = () => {
  const developmentURL = 'http://localhost:8080';
  const productURL = 'http://api.branch.xrrs.lymumu.com';

  if ('development' == process.env.NODE_ENV)
    return developmentURL;
  else if ('production' == process.env.NODE_ENV)
    return productURL;

  return productURL;
}

let API_ROOT = getApiRoot();

// 验证错误处理
function handleError(response) {
  let message;
  switch (response.status) {
    case 422: // 验证失败
      message = getValidateErrorMessage(response.data);
      break;
    case 500:
      message = response.data;
      break;
    default:
      message = '未知错误';
      break;
  }

  Notification.error({
    title: '错误',
    message: message
  });
}

function getValidateErrorMessage(data) {
  // console.log(data);
  let message;
  for (let key in data) {
    let errors = data[key];
    message = key + JSON.stringify(errors);
  }
  return message;
}

export const request = function(config) {
  config.baseURL = API_ROOT;
  // object参数的处理方法
  config.paramsSerializer = function(params) {
    return Qs.stringify(params, {
      arrayFormat: 'brackets'
    })
  };
  return new Promise((resolve, reject) => {
    axios(config).then(response => {
      // console.log('resolve', response);
      resolve(response.data);
    }).catch((error) => {
      // console.log('catch', error.response);
      handleError(error.response);
    });
  });
}

// export const projectConfig = () => {
//   let platform;
//   if (window.navigator.userAgent.indexOf('zhaoonline') > -1) {
//     platform = 'zhaoonline';
//   } else if (window.navigator.userAgent.toLowerCase().indexOf('micromessenger') > -1) {
//     platform = 'weixin';
//   } else if (window.navigator.userAgent.toLowerCase().indexOf('weibo') > -1) {
//     platform = 'weibo';
//   } else {
//     platform = 'pc';
//   }
//   return {
//     'DEVICEID': 'FBED7066-9101-40CE-8C4E-EAA22C887346',
//     'ZHAOAPPID': 'B2E7BLKUT788CCW22F93PC',
//     'WXAPPID': 'wxaa40fcdea349de54',
//     'USERACTION': '3.6.1',
//     'TZB': '3.6.1',
//     'PLATFORM': platform
//   };
// };

// export const Authentication = function(appId, key, deviceId, HttpMothod, HttpPath) {
//   var SecretAccessKey = key;
//   var SHA1 = new Hashes.SHA1(),
//     stringToSign = HttpMothod.toUpperCase() + '\n\n' + HttpPath + '\n' + deviceId,
//     signature = SHA1.b64_hmac(SecretAccessKey, stringToSign);
//   return 'ZHAO ' + appId + ':' + signature;
// };

// 添加oa统计
// if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
//   var _oatopic = "SubViewController";
// } else if (/(Android)/i.test(navigator.userAgent)) {
//   var _oatopic = "SubscribeFragment";
// }
// import Oacode from 'lib/js/oa_code';
